<template>
  <!-- 课程购买页 -->
  <div class="course">
    <van-image width="100%" height="375" fit="cover" :src="course.courseImg" />
    <div class="flex-column content">
      <div class="row-align-center">
        <span style="color:#F40404;font-size:18px;">￥{{course.intervalPrice}}</span>
        <span
          v-if="course.makingPrice != ''"
          class="line-m"
          style="font-size:12px;color:rgba(16, 16, 16, 0.45)"
        >￥{{(course.makingPrice)|fixed}}</span>
      </div>
      <p
        style="color:rgba(16, 16, 16, 0.45);font-size:10px;margin:6px 0;"
      >截止时间：{{course.salesDeadlineTime}}</p>
      <p
        style="color:rgba(16, 16, 16, 1);font-size:14px;margin:6px 0;font-weight:600;"
      >{{course.courseName}}</p>
      <p
        style="color:rgba(68, 68, 68, 1);font-size:13px;margin:0;line-height:13px"
        v-html="course.courseDescribe"
      ></p>
    </div>
    <!-- 上课地址 -->
    <div class="row-align-center address">
      <p class="notes-p">线下课</p>
      <div class="flex-row" style="font-size: 12px;width:83%">
        <van-icon
          style="margin:13px 0;"
          name="location"
          size="12"
          color="#F40404"
          v-if="course.courseAddress!=''"
        />
        <p>{{course.courseAddress}}</p>
      </div>
    </div>
    <!-- 购买须知 -->
    <div class="notes flex-row">
      <p class="notes-p">购买须知</p>
      <div class="flex-row" style="font-size: 12px;width:83%">
        <p style="margin:0 0 0 10px;">{{course.purchaseInstructions}}</p>
      </div>
    </div>
    <!-- 家长--购买按钮 -->
    <van-button
      v-if="roleType == 'parent'"
      style="position:fixed;bottom:0;"
      size="large"
      color="#FF9900"
      @click="show = true"
    >立即购买</van-button>
    <!-- 教师--底部操作按钮 -->
    <div v-else class="flex-row" style="position:fixed;bottom:0;width:100%">
      <van-button size="large" color="#6385D7" @click="show = true" plain>规格和价格</van-button>
      <van-button size="large" color="#6385D7" @click="showCollectionInfo" plain>收款信息</van-button>
      <van-button size="large" color="#6385D7" @click="promoClick">优惠码</van-button>
    </div>
    <div style="height:50px;" />
    <van-sku
      v-model="show"
      :sku="sku"
      :goods="goods"
      :goods-id="course.courseID"
      :quota="1"
      :hide-quota-text="true"
      :hide-stock="sku.hide_stock"
      :show-add-cart-btn="false"
      @buy-clicked="onBuyClicked"
      @sku-selected="skuSelected"
      :close-on-click-overlay="true"
      ref="skuRef"
    >
      <div v-if="roleType == 'teacher'" slot="sku-actions"></div>
    </van-sku>
    <van-popup v-model="collectInfoShow" round position="bottom">
      <div class="column-align-center collect-pop">
        <p style="width:100%;">线下收款方式</p>
        <p style="width:100%;font-size: 14px;margin-bottom:7px;" v-if="paymethod.cash">
          <span style="color: rgba(16, 16, 16, 0.65)">支持</span> 现金支付
        </p>
        <p style="width:100%;font-size: 14px;margin-bottom:7px;" v-if="paymethod.offline">
          <span style="color: rgba(16, 16, 16, 0.65)">支持</span> 线下移动支付
        </p>
        <van-button
          round
          color="#59BDC3"
          size="small"
          style="margin:35px 0 ;"
          @click="bindToPayCode(course)"
          v-if="paymethod.offline"
        >查看收款二维码</van-button>
      </div>
    </van-popup>
    <van-popup v-model="promoCode" round position="bottom" @click-overlay="cleanTime">
      <div class="column-align-center">
        <p style="font-size:48px">{{promo.discountCode}}</p>
        <h6 style="margin:0">优惠码将在{{promo.timespan}} 后失效</h6>
        <div class="divider" />
        <div class="row-space-between sale" style="margin-top:29px;">
          <p>分销比例</p>
          <p>{{promo.distributionRatio}}</p>
        </div>
        <div class="row-space-between sale" style="margin-bottom:29px;">
          <p>客户优惠比例</p>
          <p>{{promo.discountRatio}}</p>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getDiscountCode } from "@/api/course";
import { getReceiveQRcode } from "@/api/order";
import Qs from "qs";
import { Toast, Dialog } from "vant";
export default {
  data() {
    return {
      show: false,
      collectInfoShow: false,
      promoCode: false,
      goodsId: "1",
      sku: {},
      goods: {},
      skuList: [],
      promo: {}, //优惠信息
      time: "", //定时器
      paymethod: {
        offline: false,
        cash: false
      } //支付方式
    };
  },
  methods: {
    // 家长端--购买课程
    onBuyClicked(value) {
      // console.log(this.$refs.skuRef.selectedText);
      if (this.sku.list.length != 0) {
        let arr = this.$refs.skuRef.selectedText.split(" ");
        let list = arr[1].split("；");
        this.sku.tree.forEach((items, index) => {
          list[index] = items.k + "：" + list[index];
        });
        let skuText = list.join("/");
        var params = {
          skuText: skuText,
          price: value.selectedSkuComb.price
        };
      } else {
        var params = {
          skuText: "默认",
          price: value.selectedSkuComb.price
        };
      }
      this.$router.push({ name: "OrderConfirm", params: params });
    },
    skuSelected(value) {},
    // 职工--获取优惠码
    async getPromo() {
      Toast.loading({ forbidClick: true, duration: 0 });
      if (this.roleType == "teacher") {
        const result = await getDiscountCode({
          phoneNumber: this.phone,
          campusID: this.course.campusID,
          courseID: this.course.courseID
        });
        console.log(result);
        if (result.result == "OK" && result.data != {}) {
          this.promo = result.data;
          this.promoCode = true;
          Toast.clear()
        } else {
          this.promoCode = false;
          Toast.fail('暂无优惠码信息！')
        }
      }
    },
    promoClick() {
      // this.promoCode = true;
      // 职工--获取课程优惠码
      this.getPromo();
    },
    // 清空计时器
    cleanTime() {
      if (this.time != "") {
        clearInterval(this.time);
        this.time = "";
      }
      console.log("清空");
    },
    // 跳转收款码页面
    async bindToPayCode(value) {
      const result = await getReceiveQRcode({
        phoneNumber: this.phone,
        campusID: this.campusID,
        courseID:value.courseID
      });
      if (result.result == "Fail") {
        Dialog.alert({
          message: result.msg
        }).then(() => {
          // on close
        });
      } else if (result.data.length == 0) {
        Dialog.alert({
          message: "暂无收款二维码数据"
        }).then(() => {
          this.collectInfoShow = false;
          // on close
        });
      } else {
        this.$router.push({
          name: "PaymentCode",
          params: { course_id: value.courseID }
        });
      }
    },
    // 整理付款方式
    initAction(value) {
      // 设置支付方式
      let arr = value.split(",");
      let list = [];
      arr.forEach((item, index) => {
        switch (item) {
          case "3":
            list.push({ id: 3, name: "现金支付" });
            break;
          case "2":
            list.push({ id: 2, name: "线上支付" });
            break;
          case "1":
            list.push({ id: 1, name: "线下支付" });
            break;
        }
      });
      return list;
    },
    // 收款信息按钮
    showCollectionInfo() {
      if (this.course.paymentMethod.indexOf(1) >= 0) {
        // 支持线下支付
        this.paymethod.offline = true;
      }
      if (this.course.paymentMethod.indexOf(3) >= 0) {
        //支持现金支付
        this.paymethod.cash = true;
      }
      this.collectInfoShow = true;
    }
  },
  async created() {
    if (this.course.detailed == "") {
      this.sku = {
        none_sku: true,
        price: this.course.intervalPrice,
        list: [],
        tree: [],
        stock_num: 100
      };
      this.goods = {
        picture: this.course.courseImg,
        title: this.course.courserName
      };
    } else {
      // 初始化数据
      this.sku.tree = this.course.detailed.tree;
      this.sku.list = this.course.detailed.list;
      if (this.sku.list.length == 0) {
        // 无规格产品
        this.sku = Object.assign(this.sku, {
          none_sku: true
        });
      } else {
        // 有规格产品
        this.sku.list.forEach((item, index) => {
          this.sku.list[index] = Object.assign(
            {
              stock_num: 100,
              price: parseFloat(this.sku.list[index].prics) * 100,
              id: index + 1
            },
            this.sku.list[index]
          );
        });
      }
      this.sku.price = this.course.intervalPrice;
      this.sku = Object.assign(this.sku, { hide_stock: true, stock_num: 100 }); // 是否隐藏剩余库存
      this.goods = {
        picture: this.course.courseImg,
        title: this.course.courserName
      };
    }
  },
  computed: {
    ...mapGetters({
      course: "getCourse",
      roleType: "getRoleType",
      phone: "getPhone",
      campusID: "getCampusID"
    })
  },
  watch: {
    promo() {
      if (this.time == "") {
        console.log(this.time, "111");
        this.time = setInterval(() => {
          this.promo.timespan = this.$moment(this.promo.timespan, "HH:mm:ss")
            .subtract(1, "second")
            .format("HH:mm:ss");
          if (this.promo.timespan == "00:00:00") {
            clearInterval(this.time);
            this.time = "";
            // this.promo = {};
            //重新获取
            this.promoCode = false;
          }
        }, 1000);
        console.log(this.time);
      }
    }
  },
  filters: {
    fixed(value) {
      return parseInt(value).toFixed(2);
    }
  }
};
</script>

<style lang="scss" scoped>
.course {
  background-color: #f7f7f7;
  font-family: PingFangSC-regular;
}
.content {
  background-color: #fff;
  padding: 10px 16px;
}
.address {
  background-color: #fff;
  margin-top: 6px;
  height: 50px;
  padding: 10px 16px;
}
.notes {
  margin-top: 6px;
  padding: 20px 14px;
  background-color: #fff;
}
.notes-p {
  color: rgba(16, 16, 16, 0.65);
  font-size: 12px;
  text-align: left;
  width: 17%;
  text-align: left;
  white-space: nowrap;
  margin: 0;
}
.sale {
  width: 41%;
  p {
    opacity: 0.65;
    color: rgba(16, 16, 16, 1);
    font-size: 14px;
    margin: 5px;
  }
}
.collect-pop {
  text-align: left;
  padding: 16px 23px;
  color: rgba(16, 16, 16, 1);
}
.divider {
  height: 1px;
  border-top: 1px solid rgba(235, 235, 235, 1);
  margin-top: 80px;
  width: 90%;
}
</style>